import React, {Component} from 'react';
import {articleDetail, editArticle} from "@/pages/article/service";

import {Form, Input, Button, message} from 'antd';

import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';


class Edit extends Component {
  constructor(props) {
    super(props);
    this.state = {
      articleInfo: {},
      value: 'test',
    };
  }

  componentDidMount() {
    // 先获取文章的详情
    articleDetail(this.props.match.params.id).then(res => {
      this.setState({
        articleInfo: res.data,
        value: res.data.content
      })
    })
  }

  handleChange = (value) => {
    this.setState({
      value,
    });
  };

  onFinish(values) {
    editArticle({
      ...values,
      content:this.state.value,
      articleId: this.state.articleInfo.articleId
    }).then(res => {
      if (res.code === 0) {
        message.success("更新成功");
        this.props.history.push("/article")
      } else {
        message.error(res.msg);
      }
    })
  }

  onFinishFailed(errorInfo) {
    console.log('Failed:', errorInfo);
  }

  render() {
    const {articleInfo} = this.state;

    const layout = {
      labelCol: {span: 8},
      wrapperCol: {span: 16},
    };
    const tailLayout = {
      wrapperCol: {offset: 8, span: 16},
    };

    const modules = {
      toolbar: [
        [{'header': [1, 2, false]}],
        ['bold', 'italic', 'underline', 'strike', 'blockquote'],
        [{'list': 'ordered'}, {'list': 'bullet'}, {'indent': '-1'}, {'indent': '+1'}],
        ['link', 'image'],
        ['clean']
      ],
    }

    const formats = [
      'header',
      'bold', 'italic', 'underline', 'strike', 'blockquote',
      'list', 'bullet', 'indent',
      'link', 'image'
    ]

    return (
      <div>
        {
          articleInfo.articleId && <Form
            {...layout}
            name="basic"
            initialValues={articleInfo}
            onFinish={this.onFinish.bind(this)}
            onFinishFailed={this.onFinishFailed.bind(this)}
          >
            <Form.Item
              label="标题"
              name="title"
              rules={[{required: true, message: '请输入标题'}]}
            >
              <Input/>
            </Form.Item>

            <ReactQuill modules={modules}
                        formats={formats} value={this.state.value} onChange={this.handleChange}/>

            <Form.Item {...tailLayout}>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </Form.Item>
          </Form>
        }
      </div>
    );
  }
}


export default Edit;
